<?php

namespace App\Services\Pay\Order\Elasticsearch;

use App\Core\Traits\Numeral;
use App\Services\Service;
use App\Services\Traits\DatabaseElasticsearch;
use App\Models\Elasticsearch\Order\Wallet as Order;
use App\Exports\Pay\Elasticsearch\WalletExport;

class WalletService extends Service
{
    use DatabaseElasticsearch, Numeral;

    /**
     * 导出数据
     *
     * @param array $params
     * @param \Illuminate\Http\Request $request
     * @param bool $export
     * @return false|void
     */
    private function export($params, $request, bool $export)
    {
        if (!$export) {
            return false;
        }
        // 前端排序
        $this->makeOrderParam($request, $params);

        // 导出文件
        WalletExport::es($params, Order::class)->download();
    }

    /**
     * 获取数据列表
     *
     * @param \Illuminate\Http\Request $request
     * @param bool $export
     * @return array[]|int[]|array[]
     */
    public function getList($request, $export = false)
    {
        $params = [
            'body' => ['track_total_hits' => true],
            '_source_excludes' => ['isw_data', 'note'],
        ];

        // 筛选【平台】
        $this->makeWhereParamOrg($request, $params);
        // 筛选【时间】
        $this->makeWhereParamDatetime($request, $params, null, 'datetime', Order::INDEX_NAME);
        // 筛选【搜索】
        $this->makeWhereParamSearch($request, $params);
        // 筛选【类型】
        $this->makeWhereParam($request, 'payment', $params);
        // 筛选【状态】
        $this->makeWhereParam($request, 'status', $params);

        // 导出数据
        $this->export($params, $request, $export);

        // 排序分页
        $this->makeOrderParam($request, $params)->makePaginationParam($request, $params);
        // 统计数据
        $this->makeAggs($params, 'sum', ['usd.consume_sum', 'usd.take_back_sum']);

        // 查询数据
        $results = Order::search($params);

        // 数据列表
        $datas = $results['hits']['hits'];
        // 数据条数
        $total = $results['hits']['total']['value'];
        // 统计数据
        $stats = $this->makeStats($results['aggregations'] ?? null);

        return [
            $datas,
            $total,
            $stats
        ];
    }

    private function makeStats($aggs)
    {
        return [
            'usd' => is_null($aggs) ? null : [
                'consume' => $aggs['usd.consume_sum']['value'],
                'take_back' => $aggs['usd.take_back_sum']['value'],
            ],
        ];
    }
}
